package com.demo.base.security;

import com.demo.dtos.SysRole;
import com.demo.dtos.SysUser;
import com.demo.services.SysRoleService;
import com.demo.services.SysUserService;
import com.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *<p>Description:用户合法处理逻辑</p>
 *<p>Author:Gred</p>
 *<p>Date:2017/8/31 20:53</p>
 *<p>version:1.0</p>
 **/
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    SysUserService userService;
    @Autowired
    SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        Collection<GrantedAuthority> auths = new ArrayList<>();
        Map<String, Object> srhParams = new HashMap<>();
        srhParams.put("userAccount", username);
        SysUser user = userService.findByMap(srhParams);
        if (user == null || StringUtils.isEmpty(user.getUuid())) {
            throw new UsernameNotFoundException("用户名密码错误");
        }

        boolean enables = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;


        //获取用户的角色s
        srhParams.clear();
        srhParams.put("userUuid", user.getUuid());
        SysRole role = roleService.findRoleByLog(srhParams);

        auths.add(new SimpleGrantedAuthority(role.getRole()));
        User userdetail = new User(user.getUserAccount(), user.getUserPsw(), enables, accountNonExpired,
                credentialsNonExpired, accountNonLocked, auths);
        return userdetail;
    }
}
